package com.share.security;


import com.alibaba.fastjson.JSONObject;
import com.share.domain.Const;
import com.share.exception.CaptchaException;
import com.share.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;


/**
 * @program: share-admin
 * 描述：
 * @author: XLX
 * @create: 2022-11-30 23:15
 **/
@Component
public class CaptchaFilter extends OncePerRequestFilter{


    @Autowired
    RedisUtil redisUtil;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String url = request.getRequestURI();
        if ("/login".equals(url) && request.getMethod().equals("POST")){
            //校验验证码
            try {
                validate(request);
            }catch (CaptchaException e){
                //交给认证失败处理器
                //如果不正确，就跳转到验证失败处理器
                loginFailureHandler.onAuthenticationFailure(request,response,e);
            }

        }

        filterChain.doFilter(request,response);

    }

    //校验验证码逻辑
    private void validate(HttpServletRequest request) throws CaptchaException {
        String key = null;
        String code = null;
        code = request.getParameter("code");
        key = request.getParameter("key");

//        System.out.println(code);
        //System.out.println(code);
        System.out.println(code);
        if (StringUtils.isBlank(code) || StringUtils.isBlank(key)){
            throw new CaptchaException("验证码错误");
        }

        if (!(code.equals(redisUtil.hget(Const.CAPTCHA_KEY,key)))){
            throw new CaptchaException("验证码错误");
        }

        //验证码去掉，一次性使用
        redisUtil.hdel(Const.CAPTCHA_KEY,key);

    }
}